public class SpiralOrder {
    /**
     * 输入一个矩阵，按照从外向里以顺时针的顺序依次打印出每一个数字。
     *
     * @param matrix
     * @return
     */
    public int[] spiralOrder(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;
        int ans_len = m * n;
        int[] ans = new int[ans_len];
        boolean[][] visited = new boolean[m][n];
        if (ans_len == 0)
            return ans;
        int x=0,y=0;
        int[][] directions = {{0,1},{1,0},{0,-1},{-1,0}};
        int index = 0;
        for (int i=0;i<ans_len;i++){
            ans[i]  = matrix[x][y];
            visited[x][y] = true;
            int nextRow = x+directions[index][0];
            int nextColumn = y +directions[index][1];
            if (nextRow<0||nextColumn<0||nextRow>=m||nextColumn>=n||visited[nextRow][nextColumn]==true){
                index = (index+1)%4;
            }
            x = x + directions[index][0];
            y = y + directions[index][1];
        }
        return ans;

    }




}
